home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 7549 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.1 KB

  1. Path: keats.ugrad.cs.ubc.ca!not-for-mail
  2. From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: newbie question concerning fread
  5. Date: 25 Feb 1996 11:51:18 -0800
  6. Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
  7. Distribution: inet
  8. Message-ID: <4gqejmINNh5@keats.ugrad.cs.ubc.ca>
  9. References: <rblayney.824643669@extro>
  10. NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
  11.  
  12. In article <rblayney.824643669@extro>,
  13. Robert Blayney <rblayney@extro.ucc.su.OZ.AU> wrote:
  14. >
  15. >Hi,
  16. >    I'm attempting to use the following function call
  17. >        fread(&result, sizeof(int), 16, fp);
  18. >    Unfortunately when I attempt to print the contents of the result array
  19. >I obtain all zeros, where  result is declared:  int *result. I've tried successfully
  20.  
  21. There is your problem. Since result is already a pointer to an integer type,
  22. you don't need to apply the '&' address operator. If you do, you pass the
  23. address of the pointer itself, which is certainly not the array of integers
  24. that it points to. Practically, you end up clobbering the value of the pointer
  25. and writing some extra bytes to some variable that is stored just next to the
  26. pointer in memory (or cause a segmentation violation). Theoretically, what you
  27. are doing produces what is known as "undefined results", which means that any
  28. sort of screw up can happen according to the C standard.
  29.  
  30. >to use fgets which works on text files but really need to use fread. I'm not sure 
  31. >where the problem lies but when I've been printing the result array I've 
  32. >been using printf("%-6.2d", *(result + i));
  33.  
  34. This is okay. However, you might also avail yourself of using the following
  35. notation instead of *(result + i):
  36.  
  37.     result[i]
  38.  
  39. The two are equivalent, since in C, an "E1[E2]", where E1 and E2 are
  40. expressions,  is the same as *((E1) + (E2)). One neat effect of this definition
  41. is that if you have an array called 'a', and an index called 'i', you can refer
  42. to the ith element as either a[i] or i[a]. Hence both of these constructs give
  43. the letter 'x':
  44.  
  45.     char x = "abcx"[3];
  46.     char x = [3]"abcx";
  47.     char x = ["abcx"]3;
  48.     char x = 3["abcx"];
  49.  
  50. All that matters is that one operand is a pointer, and one an integer.
  51. -- 
  52.  
  53.